package persistenceAndSerialization;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class StudentPersisdent {

	public static void main(String[] args) {
		Student jack=new Student("jack","male",25);
		System.out.println("student1:"+jack.hashCode());
		System.out.println("student1:"+jack);
		persist(jack);
		
		Student jack2=load();
		System.out.println("student2:"+jack2);
		System.out.println("student2:"+jack2.hashCode());
	}
	private static void persist(Student student){
		ObjectOutputStream oos = null;
		try {
			oos=new ObjectOutputStream(new FileOutputStream("student.out"));
			oos.writeObject(student);
			oos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(oos !=null){
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static Student load(){
		ObjectInputStream ois=null;
		try {
			ois=new ObjectInputStream(new FileInputStream("student.out"));
			return  (Student)ois.readObject();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally {
			if(ois != null){
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;	
	}
}
